package com.example.window;

import com.example.bean.WaterSenSorFunction;
import com.example.bean.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.datastream.WindowedStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;

/**
 * Created with IntelliJ IDEA.
 * ClassName: WindowRdeuceDemo
 * Package: com.example.window
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-07-19
 * Time: 17:41
 */

public class WindowAggregateDemo {

    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env =
                StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> data = env.socketTextStream("hadoop102", 7777)
                .map(new WaterSenSorFunction());

        KeyedStream<WaterSensor, String> sensorKS = data.keyBy(value -> value.getId());

        //1.窗口 增量聚合函数 规约聚合 Reduce
        //1.窗口分配器
        //滚动窗口
        WindowedStream<WaterSensor, String, TimeWindow> sensorWS =
                sensorKS.window(TumblingProcessingTimeWindows.of(Time.seconds(10)));

        //窗口 聚合函数
        //AggregateFunction 参数为 输入数据的类型  累加器:累加过程数据的类型 输出数据的类型
        SingleOutputStreamOperator<String> aggregate = sensorWS.aggregate(new AggregateFunction<WaterSensor, Integer, String>() {
            //1.属于本窗口的第一条数据 创建窗口 创建累加器
            //2.增量聚合 来一条计算一条 调用add方法
            //3.窗口输出时调用一次getResult方法
            //4.输入 中间累加器 输出 类型可以不一样 非常灵活
            @Override
            public Integer createAccumulator() {
                System.out.println("创建累加器");
                //初始化累加器
                return 0;
            }
            @Override
            public Integer add(WaterSensor value, Integer accumulator) {
                //accumulator 就是之前的计算逻辑
                System.out.println("调用add 累加逻辑 value= " + value);
                return value.getVc() + accumulator;
            }
            @Override
            public String getResult(Integer accumulator) {
                //窗口触发时候输出
                System.out.println("调用getResult");
                return accumulator.toString();
            }
            @Override
            public Integer merge(Integer a, Integer b) {
                //一般不会用到 只有会话窗口用到
                System.out.println("merge调用");
                return null;
            }
        });

        aggregate.print();
        env.execute();
    }

}
